import re
import random
import socket
import urllib
import urllib2

from django.core.management.base import BaseCommand

from BeautifulSoup import BeautifulSoup
from mobile.models import Entry

class Command(BaseCommand):
    help = "Sniff CAPV city entries"
    
    requires_model_validation = True
    
    def handle(self, *app_labels, **options):
        #Get site
        ff_version = "%s.%s.%s.%s" % tuple([random.randint(0,3) for i in range(4)])
        user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/%s" % ff_version #CAPV no te enfades con Firefox
        url = "http://www.trafikoa.net/public/wps/portal/trafico/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4s3cjcBSZnFO8ZbeulHogt5IoR8PfJzU_WD9L31A_QLckMjyh0dFQEy3Jpe/delta/base64xml/L3dJdyEvd0ZNQUFzQUMvNElVRS82X0ZfMkc3"
        headers = { 'User-Agent' : user_agent }
        socket.setdefaulttimeout(10)
        req = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(req)
        data = response.read()
    
        #Process
        soup = BeautifulSoup(data)
        soup = soup.findAll('div',id="cuerpoPag")[0]
        tablas = soup.findAll('table',width="50%", border="0")
        tablas = [tablas[i] for i in (1,3,5)]
        
        for t in tablas:
            accesos = t.findAll('tr')
            for acceso in accesos:
                try:
                    name = unicode(acceso.findAll('td', width="140")[0].string)
                    estado = unicode(acceso.findAll('td', width="100")[0].string.replace('\n',''))
                    
                    entry, new_entry = Entry.objects.get_or_create(name=name)
                    entry.set_estado(estado)
                except:
                    pass